<!DOCTYPE html>
<html lang="en">
<head><!-- hexo injector head_begin start -->
        <link rel="preconnect" href="https://blog.fantasyke.cn/picx-images-hosting" crossorigin=""><!-- hexo injector head_begin end -->
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/uploads/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/uploads/avatar.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="0qBBGdG7vYORyT5XLZRUqQZ_y5kKYhgyUwNqjSIImg0">
  <meta name="msvalidate.01" content="63C90D0EC3DA6C31FD109132B7BEF502">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Zen+Maru+Gothic:300,300italic,400,400italic,700,700italic%7CZCOOL+XiaoWei:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css" integrity="sha256-5eIC48iZUHmSlSUz9XtjRyK2mzQkHScZY1WdMaoz74E=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.31/fancybox/fancybox.css" integrity="sha256-gkQVf8UKZgQ0HyuxL/VnacadJ+D2Kox2TCEBuNQg5+w=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.fantasyke.cn","root":"/","images":"/images","scheme":"Mist","darkmode":false,"version":"8.21.1","exturl":true,"sidebar":{"position":"right","width_expanded":350,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":null},"fold":{"enable":true,"height":500},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":true,"nav":{"gitalk":{"text":"gitalk","order":-1}},"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="概念   简介   特征   应用">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis基础">
<meta property="og:url" content="https://blog.fantasyke.cn/posts/26216/index.html">
<meta property="og:site_name" content="Fantasy&#39;Ke Blog">
<meta property="og:description" content="概念   简介   特征   应用">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/redis/image.8ada3v182u.webp">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/redis/image.2dopwukw63.webp">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/redis/image.5c100ctctw.webp">
<meta property="og:image" content="https://fantasy-ke.github.io/picx-images-hosting/redis/image.2krxsa7crt.webp">
<meta property="article:published_time" content="2023-05-29T02:19:00.000Z">
<meta property="article:modified_time" content="2024-12-17T06:36:35.394Z">
<meta property="article:author" content="Fantasy-ke">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="NOSQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fantasy-ke.github.io/picx-images-hosting/redis/image.8ada3v182u.webp">


<link rel="canonical" href="https://blog.fantasyke.cn/posts/26216/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"en","comments":true,"permalink":"https://blog.fantasyke.cn/posts/26216/","path":"posts/26216/","title":"Redis基础"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Redis基础 | Fantasy'Ke Blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<link rel="alternate" href="/atom.xml" title="Fantasy'Ke Blog" type="application/atom+xml">
<style>.darkmode--activated{--body-bg-color:#282828;--content-bg-color:#333;--card-bg-color:#555;--text-color:#ccc;--blockquote-color:#bbb;--link-color:#ccc;--link-hover-color:#eee;--brand-color:#ddd;--brand-hover-color:#ddd;--table-row-odd-bg-color:#282828;--table-row-hover-bg-color:#363636;--menu-item-bg-color:#555;--btn-default-bg:#222;--btn-default-color:#ccc;--btn-default-border-color:#555;--btn-default-hover-bg:#666;--btn-default-hover-color:#ccc;--btn-default-hover-border-color:#666;--highlight-background:#282b2e;--highlight-foreground:#a9b7c6;--highlight-gutter-background:#34393d;--highlight-gutter-foreground:#9ca9b6}.darkmode--activated img{opacity:.75}.darkmode--activated img:hover{opacity:.9}.darkmode--activated code{color:#69dbdc;background:0 0}button.darkmode-toggle{z-index:9999}.darkmode-ignore,img{display:flex!important}.beian img{display:inline-block!important}</style></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Fantasy'Ke Blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="Search" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a></li><li class="menu-item menu-item-photos"><a href="/photos/" rel="section"><i class="fas fa-camera-retro fa-fw"></i>photos</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="Searching..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link"><span class="nav-number">1.</span> <span class="nav-text"> 概念</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-2"><span class="nav-number">1.1.</span> <span class="nav-text"> 简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-3"><span class="nav-number">1.2.</span> <span class="nav-text"> 特征</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-4"><span class="nav-number">1.3.</span> <span class="nav-text"> 应用</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-5"><span class="nav-number">2.</span> <span class="nav-text"> 数据类型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-6"><span class="nav-number">2.1.</span> <span class="nav-text"> string</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-7"><span class="nav-number">2.1.1.</span> <span class="nav-text"> 基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-8"><span class="nav-number">2.1.2.</span> <span class="nav-text"> set与mset</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-9"><span class="nav-number">2.1.3.</span> <span class="nav-text"> 扩展操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#-10"><span class="nav-number">2.1.3.1.</span> <span class="nav-text"> 业务场景A</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-11"><span class="nav-number">2.1.3.2.</span> <span class="nav-text"> 业务场景B</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-12"><span class="nav-number">2.1.3.3.</span> <span class="nav-text"> 业务场景C</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-13"><span class="nav-number">2.1.4.</span> <span class="nav-text"> key的设置约定</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-14"><span class="nav-number">2.1.5.</span> <span class="nav-text"> 注意事项</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-15"><span class="nav-number">2.2.</span> <span class="nav-text"> hash</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-16"><span class="nav-number">2.2.1.</span> <span class="nav-text"> 基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-17"><span class="nav-number">2.2.2.</span> <span class="nav-text"> 扩展操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-18"><span class="nav-number">2.2.3.</span> <span class="nav-text"> 注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-19"><span class="nav-number">2.2.4.</span> <span class="nav-text"> 应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#-20"><span class="nav-number">2.2.4.1.</span> <span class="nav-text"> 业务场景A</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-21"><span class="nav-number">2.2.4.2.</span> <span class="nav-text"> 业务场景B</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-22"><span class="nav-number">2.2.5.</span> <span class="nav-text"> string存对象(json)和hash寸对象</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-23"><span class="nav-number">2.3.</span> <span class="nav-text"> list</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-24"><span class="nav-number">2.3.1.</span> <span class="nav-text"> 基础操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-25"><span class="nav-number">2.3.2.</span> <span class="nav-text"> 扩展操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-26"><span class="nav-number">2.3.3.</span> <span class="nav-text"> 应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#-27"><span class="nav-number">2.3.3.1.</span> <span class="nav-text"> 业务场景A</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-28"><span class="nav-number">2.3.4.</span> <span class="nav-text"> 注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-29"><span class="nav-number">2.3.5.</span> <span class="nav-text"> 比较典型的业务场景</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-30"><span class="nav-number">2.4.</span> <span class="nav-text"> set</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-31"><span class="nav-number">2.4.1.</span> <span class="nav-text"> 基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-32"><span class="nav-number">2.4.2.</span> <span class="nav-text"> 扩展操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-33"><span class="nav-number">2.4.3.</span> <span class="nav-text"> 应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#-34"><span class="nav-number">2.4.3.1.</span> <span class="nav-text"> 业务场景A</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-35"><span class="nav-number">2.4.3.2.</span> <span class="nav-text"> 业务场景B</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-36"><span class="nav-number">2.4.3.3.</span> <span class="nav-text"> 业务场景C</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-37"><span class="nav-number">2.4.3.4.</span> <span class="nav-text"> 业务场景D</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-38"><span class="nav-number">2.4.3.5.</span> <span class="nav-text"> 业务场景E</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-39"><span class="nav-number">2.4.4.</span> <span class="nav-text"> 注意事项</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-40"><span class="nav-number">2.5.</span> <span class="nav-text"> sorted_set</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#-41"><span class="nav-number">2.5.1.</span> <span class="nav-text"> 基础操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-42"><span class="nav-number">2.5.2.</span> <span class="nav-text"> 应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#-43"><span class="nav-number">2.5.2.1.</span> <span class="nav-text"> 业务场景A</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-44"><span class="nav-number">2.5.2.2.</span> <span class="nav-text"> 业务场景B</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#-45"><span class="nav-number">2.5.2.3.</span> <span class="nav-text"> 业务场景C</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#-46"><span class="nav-number">2.5.3.</span> <span class="nav-text"> 注意事项</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-47"><span class="nav-number">3.</span> <span class="nav-text"> 实践案例</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-48"><span class="nav-number">3.1.</span> <span class="nav-text"> 业务场景A</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-49"><span class="nav-number">3.2.</span> <span class="nav-text"> 业务场景B</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-50"><span class="nav-number">4.</span> <span class="nav-text"> key通用操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-51"><span class="nav-number">4.1.</span> <span class="nav-text"> key基本操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-52"><span class="nav-number">4.2.</span> <span class="nav-text"> key的时效性控制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-53"><span class="nav-number">4.3.</span> <span class="nav-text"> key的查询模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-54"><span class="nav-number">4.4.</span> <span class="nav-text"> key的其他操作</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#-55"><span class="nav-number">5.</span> <span class="nav-text"> 数据库通用操作</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#-56"><span class="nav-number">5.1.</span> <span class="nav-text"> key的重复问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-57"><span class="nav-number">5.2.</span> <span class="nav-text"> 基本操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#-58"><span class="nav-number">5.3.</span> <span class="nav-text"> 其他操作</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Fantasy-ke"
      src="/uploads/avatar.png">
  <p class="site-author-name" itemprop="name">Fantasy-ke</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">36</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhbnRhc3kta2U=" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;fantasy-ke"><i class="fab fa-github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly94LmNvbS9BX0RyZWFtZXJfSGFyZA==" title="Twitter → https:&#x2F;&#x2F;x.com&#x2F;A_Dreamer_Hard"><i class="fab fa-twitter fa-fw"></i>Twitter</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly93d3cueW91dHViZS5jb20vQCVFNSU5MSVBOCVFNiVBMiVBNi16OWk=" title="YouTube → https:&#x2F;&#x2F;www.youtube.com&#x2F;@%E5%91%A8%E6%A2%A6-z9i"><i class="fab fa-youtube fa-fw"></i>YouTube</span>
      </span>
  </div>
<div class="cc-license animated" itemprop="sponsor">
  <a href="https://www.netlify.com" class="cc-opacity" title="Deploy with Netlify → https://www.netlify.com" target="_blank"><img width="80" src="https://www.netlify.com/img/global/badges/netlify-dark.svg" alt="Netlify"></a>
</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css">
<div id="aplayer" style="position:relative;left;0;bottom:0;"></div>
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/color-thief-don@2.0.2/src/color-thief.js"></script>
<script>
  const ap = new APlayer({
    container: document.getElementById('aplayer'),
    autoplay: false, //自动播放
    listFolded: true, //播放列表默认折叠
    listMaxHeight: 90, //播放列表最大高度
    order: 'list', //音频循环顺序, 可选值: 'list', 'random'
    loop: 'all', //音频循环播放, 可选值: 'all', 'one', 'none'
    theme: '#e9e9e9', //切换音频时的主题色，优先级低于audio.theme
    preload: 'none', //音频预加载，可选值: 'none', 'metadata', 'auto'
    mutex: true, //互斥，阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
    lrcType: 3, //歌词格式，可选值：3（LRC文件歌词格式），1（JS字符串歌词格式）
    volume: 0.7, //默认音量，请注意播放器会记忆用户设置，用户手动设置音量后默认音量即失效
    fixed: false, //吸底模式（fixed:true），迷你模式（mini:true），普通模式（注释此行或者设置fixed:false）
    audio: [{
        name: '平凡之路',
        artist: '朴树',
        lrc: '/downloads/lrc/平凡之路-朴树.lrc',
        cover: 'http://p2.music.126.net/W_5XiCv3rGS1-J7EXpHSCQ==/18885211718782327.jpg?param=300x300',
        url: 'http://ws.stream.qqmusic.qq.com/C4000007nRJ74eQsF6.m4a?guid=942726817&vkey=64755357C5716983BEECE2981FEC3954F0DD03E7630EFF769D9C40C31F50D53E7D260CB63E22CE8F954B1144083716A1BABFC2093F8F1C14&uin=&fromtag=120032'
      },
      {
        name: '后会无期',
        artist: '徐良,汪苏泷',
        lrc: '/downloads/lrc/后会无期-G.E.M.邓紫棋.lrc',
        cover: 'http://p1.music.126.net/vpvPajo3kn88nHc7jUjeWQ==/5974746185758035.jpg?param=300x300',
        url: 'http://ws.stream.qqmusic.qq.com/C400004ECnYg0QNchK.m4a?guid=893251117&vkey=D9DCBB8C4A4CAF8550E97A2A574DE1231DFDD8BC0989CC724742C7B9831C4108E0A805A46E0F2B2A556228467C146B9C312E3E8B498614C7&uin=&fromtag=120032'
      }
    ]
  });

  // 实现切换音频时，根据音频的封面图片自适应主题色
  const colorThief = new ColorThief();
  const setTheme = (index) => {
    if (!ap.list.audios[index].theme) {
      colorThief.getColorAsync(ap.list.audios[index].cover, function(color) {
        ap.theme(`rgb(${color[0]}, ${color[1]}, ${color[2]})`, index);
      });
    }
  };
  setTheme(ap.list.index);
  ap.on('listswitch', (data) => {
    setTheme(data.index);
  });
</script>



        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          Links
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9mYW50YXN5LWtlLmdpdGh1Yi5pbw==" title="https:&#x2F;&#x2F;fantasy-ke.github.io">SunBlog</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9mYW50YXN5LWtlLmdpdGh1Yi5pbw==" title="https:&#x2F;&#x2F;fantasy-ke.github.io">做梦的努力者</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0ZhbnRhc3ktS2U=" title="https:&#x2F;&#x2F;github.com&#x2F;Fantasy-Ke">github</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9naXRlZS5jb20vZmFudGFzeV9rZQ==" title="https:&#x2F;&#x2F;gitee.com&#x2F;fantasy_ke">gitee</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly93d3cuY25ibG9ncy5jb20vZmFudGFzeS1rZQ==" title="https:&#x2F;&#x2F;www.cnblogs.com&#x2F;fantasy-ke">我的园子</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9hYnAuaW8v" title="https:&#x2F;&#x2F;abp.io&#x2F;">abp</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9hYnAuaW8vZG9jcy9sYXRlc3Qv" title="https:&#x2F;&#x2F;abp.io&#x2F;docs&#x2F;latest&#x2F;">abp doc</span>
            </li>
            <li class="links-of-blogroll-item">
              <span class="exturl" data-url="aHR0cHM6Ly9ibG9ncy5tYXNhc3RhY2suY29tLw==" title="https:&#x2F;&#x2F;blogs.masastack.com&#x2F;">masa blog</span>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="https://blog.fantasyke.cn/posts/26216/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/avatar.png">
      <meta itemprop="name" content="Fantasy-ke">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Fantasy'Ke Blog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Redis基础 | Fantasy'Ke Blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Redis基础
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2023-05-29 10:19:00" itemprop="dateCreated datePublished" datetime="2023-05-29T10:19:00+08:00">2023-05-29</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2024-12-17 14:36:35" itemprop="dateModified" datetime="2024-12-17T14:36:35+08:00">2024-12-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E6%9D%82%E4%B8%83%E6%9D%82%E5%85%AB%E7%9A%84%E7%A0%96/" itemprop="url" rel="index"><span itemprop="name">杂七杂八的砖</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="Views" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">Views: </span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="Word count in article">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">Word count in article: </span>
      <span>6k</span>
    </span>
    <span class="post-meta-item" title="Reading time">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">Reading time &asymp;</span>
      <span>22 mins.</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><!-- more -->
<!-- - [概念](#概念)
  - [简介](#简介)
  - [特征](#特征)
  - [应用](#应用)
- [数据类型](#数据类型)
  - [string](#string)
    - [`set`与`mset`](#set与mset)
    - [扩展操作](#扩展操作)
      - [业务场景A](#业务场景a)
      - [业务场景B](#业务场景b)
      - [业务场景C](#业务场景c)
    - [key的设置约定](#key的设置约定)
    - [注意事项](#注意事项)
  - [hash](#hash)
    - [基本操作](#基本操作)
    - [扩展操作](#扩展操作-1)
    - [应用场景](#应用场景)
      - [业务场景A](#业务场景a-1)
      - [业务场景B](#业务场景b-1)
    - [string存对象(json)和hash寸对象](#string存对象json和hash寸对象)
  - [list](#list)
    - [基础操作](#基础操作)
    - [扩展操作](#扩展操作-2)
    - [应用场景](#应用场景-1)
      - [业务场景A](#业务场景a-2)
    - [注意事项](#注意事项-1)
    - [比较典型的业务场景](#比较典型的业务场景)
  - [set](#set)
    - [基本操作](#基本操作-1)
    - [扩展操作](#扩展操作-3)
    - [应用场景](#应用场景-2)
      - [业务场景A](#业务场景a-3)
      - [业务场景B](#业务场景b-2)
      - [业务场景C](#业务场景c-1)
      - [业务场景D](#业务场景d)
      - [业务场景E](#业务场景e)
    - [注意事项](#注意事项-2)
  - [sorted\_set](#sorted_set)
    - [基础操作](#基础操作-1)
    - [应用场景](#应用场景-3)
      - [业务场景A](#业务场景a-4)
      - [业务场景B](#业务场景b-3)
      - [业务场景C](#业务场景c-2)
    - [注意事项](#注意事项-3)
- [实践案例](#实践案例)
  - [业务场景A](#业务场景a-5)
  - [业务场景B](#业务场景b-4)
- [key通用操作](#key通用操作)
  - [key基本操作](#key基本操作)
  - [key的时效性控制](#key的时效性控制)
  - [key的其他操作](#key的其他操作)
- [数据库通用操作](#数据库通用操作)
  - [key的重复问题](#key的重复问题)
  - [基本操作](#基本操作-2)
  - [其他操作](#其他操作) -->
<h1 id=""><a class="markdownIt-Anchor" href="#"></a> <a href="#%E6%A6%82%E5%BF%B5" title="概念"></a>概念</h1>
<h2 id="-2"><a class="markdownIt-Anchor" href="#-2"></a> <a href="#%E7%AE%80%E4%BB%8B" title="简介"></a>简介</h2>
<p>Redis：Remote Dictionary Server，使用C语言开发的一个开源的高性能键值对(key-value)数据库</p>
<h2 id="-3"><a class="markdownIt-Anchor" href="#-3"></a> <a href="#%E7%89%B9%E5%BE%81" title="特征"></a>特征</h2>
<ol>
<li>数据间没有必然的关联关系</li>
<li>内部采用单线程机制进行工作</li>
<li>高性能。官方提供测试数据，50个并发执行100000个请求，读的速度是110000次/秒，写的速度是81000次/秒</li>
<li>多数据类型支持
<ol>
<li>字符串类型 <code>string</code></li>
<li>列表类型 <code>list</code></li>
<li>散列类型 <code>hash</code></li>
<li>集合类型 <code>set</code></li>
<li>有序集合类型 <code>sorted_set</code></li>
</ol>
</li>
<li>持久化支持，可以进行数据灾难恢复</li>
</ol>
<h2 id="-4"><a class="markdownIt-Anchor" href="#-4"></a> <a href="#%E5%BA%94%E7%94%A8" title="应用"></a>应用</h2>
<ul>
<li>为热点数据加速查询(主要场景)，如热点商品、热点新闻、热点资讯、推广类高访问量信息等</li>
<li>任务队列，如秒杀、抢购、购票排队等</li>
<li>即时信息查询，如排行榜、各类网站访问统计、公交到站信息、在线人数信息、设备信号等</li>
<li>分布式数据共享，如分布式集群架构中的session分离</li>
<li>消息队列</li>
<li>分布式锁</li>
</ul>
<h1 id="-5"><a class="markdownIt-Anchor" href="#-5"></a> <a href="#%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B" title="数据类型"></a>数据类型</h1>
<h2 id="-6"><a class="markdownIt-Anchor" href="#-6"></a> <a href="#string" title="string"></a>string</h2>
<ul>
<li>
<p>存储的数据：单个数据，最简单的数据存储类型，也是最常用的数据存储类型</p>
</li>
<li>
<p>存储数据的格式：一个存储空间保存一个数据</p>
</li>
<li>
<p>存储内容：通常使用字符串，如果字符串以整数的形式展示，可以作为数字操作使用</p>
<h3 id="-7"><a class="markdownIt-Anchor" href="#-7"></a> <a href="#%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C" title="基本操作"></a>基本操作</h3>
</li>
<li>
<p>添加/修改数据：<code>set key value</code></p>
</li>
<li>
<p>获取数据：<code>get key</code></p>
</li>
<li>
<p>删除数据：<code>del key</code></p>
</li>
<li>
<p>添加/修改多个数据：<code>mset key1 value1 key2 value2 ...</code></p>
</li>
<li>
<p>获取多个数据：<code>mge key1 key2 ...</code></p>
</li>
<li>
<p>获取数据字符串个数(字符串长度)：<code>strlen key</code></p>
</li>
<li>
<p>追加信息到原始信息候补(如果原始信息存在就追加，否则新建)：<code>append key value</code></p>
</li>
</ul>
<h3 id="-8"><a class="markdownIt-Anchor" href="#-8"></a> <a href="#set%E4%B8%8Emset" title="set与mset"></a><code>set</code>与<code>mset</code></h3>
<p>需要考虑以下几个点：</p>
<ul>
<li><code>set</code>是一条指令条操作一条数据，<code>mset</code>是一条指令操作多条记录。<strong>指令的传输和响应都需要耗时</strong></li>
<li>redis是单线程执行指令，在执行指令的时候需要耗时，如果<code>mset</code>包含的数据太多，<strong>会阻塞redis</strong></li>
<li>所以：一般少量数据两者影响不大，大量数据分割成合适的大小，再多次使用<code>mset</code>，这样能减少指令传输耗时和减少redis阻塞时间</li>
</ul>
<h3 id="-9"><a class="markdownIt-Anchor" href="#-9"></a> <a href="#%E6%89%A9%E5%B1%95%E6%93%8D%E4%BD%9C" title="扩展操作"></a>扩展操作</h3>
<h4 id="-10"><a class="markdownIt-Anchor" href="#-10"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFA" title="业务场景A"></a>业务场景A</h4>
<p>大型企业级应用中，分表操作时基本操作，使用多张表存储同类型数据，但是对应的主键id必须保证统一性，不能重复。Oracle数据库具有sequence设定，可以解决该问题，但是MySql数据库并不具有类似的机制，怎么解决？</p>
<p><strong>解决方案</strong></p>
<ul>
<li>
<p>设置数值数据增加指定范围的值</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">incr key  </span><br><span class="line">incrby key increment  </span><br><span class="line">incrbyfloat ket increment </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>设置数值数据减少指定范围的值</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">decr key  </span><br><span class="line">decr key increment  </span><br></pre></td></tr></table></figure>
<p>string作为数值操作</p>
</li>
<li>
<p>string在redis内部存储默认就是一个字符串，当遇到增减类操作incr、decr时会转成数值型进行计算</p>
</li>
<li>
<p>redis所有的操作都是原子性的，采用单线程处理所有业务，命令是一个一个执行的，因此无需考虑并发带来的数据影响</p>
</li>
<li>
<p>注意：按数值进行操作的数据，如果原始数据不能转成数值，或超越了redis数值上线范围，将报错</p>
</li>
</ul>
<hr />
<h4 id="-11"><a class="markdownIt-Anchor" href="#-11"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFB" title="业务场景B"></a>业务场景B</h4>
<p>活动海选投票，只能通过微信投票，每个微信号每4小时只能投1票。</p>
<p>电商商家开启热门商品推荐，热门商品不能一直处于热门期，每个商品热门期持续3天，3天后自动取消热门</p>
<p>新闻网站会出现热点新闻，热点新闻最大的特征就是时效性，如何自动控制热点新闻的时效性</p>
<p><strong>解决方案</strong></p>
<ul>
<li>
<p>设置数据具有指定的生命周期</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">setex key seconds value  </span><br><span class="line">psetex key milliseconds value  </span><br></pre></td></tr></table></figure>
<p><strong>redis控制数据的生命周期，通过数据是否失效控制业务行为，适用于所有具有时效性限定控制的操作</strong></p>
</li>
</ul>
<hr />
<h4 id="-12"><a class="markdownIt-Anchor" href="#-12"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFC" title="业务场景C"></a>业务场景C</h4>
<p>主页高频访问信息显示控制，例如新浪微博大V主页显示粉丝数和微博数量</p>
<p><strong>解决方案</strong></p>
<ul>
<li>
<p>在redis中为大V用户设定用户信息，以用户主键和属性值为key，后台设定定时刷新策略即可</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">eg -&gt;  user:<span class="built_in">id</span>:544935942:fans  -&gt; 120658  </span><br><span class="line">eg -&gt;  user:<span class="built_in">id</span>:544935942:blogs -&gt; 6164  </span><br><span class="line">eg -&gt;  user:<span class="built_in">id</span>:544935942:focuss -&gt; 100  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>在redis中以json格式存储大V用户信息，定时刷新(也可以使用hash类型)</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eg -&gt; user:<span class="built_in">id</span>:544935942 -&gt; &#123;<span class="built_in">id</span>:544935942,name:张三,fans:120658,blogs:6164,focuss:100&#125;  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p><em>redis应用于各种结构性和非结构性高热度数据访问加速*</em></p>
</li>
</ul>
<h3 id="-13"><a class="markdownIt-Anchor" href="#-13"></a> <a href="#key%E7%9A%84%E8%AE%BE%E7%BD%AE%E7%BA%A6%E5%AE%9A" title="key的设置约定"></a>key的设置约定</h3>
<p>数据库中的热点数据key命名惯例，以<code>:</code>拼接</p>
<table>
<thead>
<tr>
<th></th>
<th>表名</th>
<th>主键名</th>
<th>主键值</th>
<th>字段名</th>
</tr>
</thead>
<tbody>
<tr>
<td>eg1：</td>
<td>order</td>
<td>id</td>
<td>20230415</td>
<td>name</td>
</tr>
<tr>
<td>eg2：</td>
<td>equip</td>
<td>id</td>
<td>82295157</td>
<td>type</td>
</tr>
<tr>
<td>eg3：</td>
<td>news</td>
<td>id</td>
<td>544935942</td>
<td>title</td>
</tr>
</tbody>
</table>
<h3 id="-14"><a class="markdownIt-Anchor" href="#-14"></a> <a href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9" title="注意事项"></a>注意事项</h3>
<ul>
<li>数据操作不成功的反馈与数据正常操作之间的差异
<ul>
<li>表示运行结果是否成功
<ul>
<li>(integer)0 -&gt; false -&gt; 失败</li>
<li>(integer)1 -&gt; true -&gt; 成功</li>
</ul>
</li>
<li>表示运行结果值
<ul>
<li>(integer)3 -&gt; 表示3个</li>
<li>(integer)1 -&gt; 表示1个</li>
</ul>
</li>
</ul>
</li>
<li>数据未获取到
<ul>
<li>(nill) -&gt; null</li>
</ul>
</li>
<li>数据最大存储量
<ul>
<li>512MB</li>
</ul>
</li>
<li>数值计算有最大范围</li>
</ul>
<h2 id="-15"><a class="markdownIt-Anchor" href="#-15"></a> <a href="#hash" title="hash"></a>hash</h2>
<ul>
<li>新的存储需求：对一系列存储的数据进行编组，方便管理，典型应用存储对象信息</li>
<li>需要的存储结构：一个存储空间保存多个键值对数据</li>
<li>hash存储结构优化
<ul>
<li>如果field数量较少，存储结构优化为类数组结构</li>
<li>如果field数量较多，存储结构使用HashMap结构</li>
</ul>
</li>
</ul>
<h3 id="-16"><a class="markdownIt-Anchor" href="#-16"></a> <a href="#%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C-1" title="基本操作"></a>基本操作</h3>
<ul>
<li>添加/修改单条数据：<code>hset key field value</code></li>
<li>获取指定field数据：<code>hget key field</code></li>
<li>获取全部field数据：<code>hgetall key</code></li>
<li>删除数据：<code>hdel key field1 field2 ...</code></li>
<li>添加/修改多条数据：<code>hmset key field1 value1 field2 value2 ...</code></li>
<li>获取多条数据：<code>hmget key field1 field2 ...</code></li>
<li>获取hash表中字段的数量：<code>hlen key</code></li>
<li>获取hash表中是否存在指定的字段：<code>hexists key field</code></li>
</ul>
<h3 id="-17"><a class="markdownIt-Anchor" href="#-17"></a> <a href="#%E6%89%A9%E5%B1%95%E6%93%8D%E4%BD%9C-1" title="扩展操作"></a>扩展操作</h3>
<ul>
<li>
<p>获取hash表中所有的字段或字段值</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hkeys key  </span><br><span class="line">hvals key  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>设置指定字段的数值数据增加指定范围的值</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hincrby key field increment  </span><br><span class="line">hincrbyfloat key field increment  </span><br></pre></td></tr></table></figure>
<h3 id="-18"><a class="markdownIt-Anchor" href="#-18"></a> <a href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9-1" title="注意事项"></a>注意事项</h3>
</li>
<li>
<p>hash类型下的value只能存储字符串，不允许存储其他数据类型，不存在嵌套现象，如果数据未获取到，对应值为nil</p>
</li>
<li>
<p>每个hash可以存储2的32次方-1个键值对</p>
</li>
<li>
<p>hash类型十分贴近对象的数据存储形式，并且可以灵活添加删除对象属性，但hash设计初衷不是为了存储大量对象而设计的，切记不可滥用，更不可以将hash作为对象列表使用</p>
</li>
</ul>
<h3 id="-19"><a class="markdownIt-Anchor" href="#-19"></a> <a href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF" title="应用场景"></a>应用场景</h3>
<h4 id="-20"><a class="markdownIt-Anchor" href="#-20"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFA-1" title="业务场景A"></a>业务场景A</h4>
<p>电商网站购物车设计与实现</p>
<p>解决方案：</p>
<ul>
<li>
<p>仅分析购物车的redis存储模型：添加、浏览、更改数量、删除、清空</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">用户Id -&gt; Key  </span><br><span class="line">购物车商品Id/SkuId -&gt; field  </span><br><span class="line">购物车商品数量 -&gt; value  </span><br><span class="line">  </span><br><span class="line">添加商品 -&gt; hset  </span><br><span class="line">修改数量 -&gt; hset/hincrby  </span><br><span class="line">删除商品 -&gt; hdel  </span><br><span class="line">商品条目数 -&gt; hlen  </span><br><span class="line">商品总数 -&gt; <span class="built_in">sum</span>(hvals)  </span><br><span class="line">浏览商品 -&gt; hgetall  </span><br></pre></td></tr></table></figure>
<ul>
<li>
<p>按照上述的操作方式，可以发现redis中只存储了购物车的商品id和商品数量，并未存储商品信息，这样在查询整个购物车的时候，还需要二次查询商品信息，所以还需要做改进，可以将商品提取到单独一个hash中</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">key -&gt; shoppingcart:product.info  </span><br><span class="line">field -&gt; 商品Id:info  </span><br><span class="line">value -&gt; 商品信息  </span><br><span class="line">  </span><br><span class="line">当用户添加商品到购物车的时候，通过 hsetnx key field value将商品存入shoppingcart:product.info，这样做可以避免重复添加商品到<span class="built_in">hash</span>中  </span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h4 id="-21"><a class="markdownIt-Anchor" href="#-21"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFB-1" title="业务场景B"></a>业务场景B</h4>
<p>销售手机充值卡的商家对移动、联通、电信的30元、50元、100元的商品退出抢购活动，每种商品抢购上线1000长</p>
<p>解决方案：</p>
<ul>
<li>以商家id作为key</li>
<li>将参与抢购的商品id作为field</li>
<li>将参与抢购的商品数量作为对应的value</li>
<li>抢购时使用降值得方式控制产品数量</li>
</ul>
<h3 id="-22"><a class="markdownIt-Anchor" href="#-22"></a> <a href="#string%E5%AD%98%E5%AF%B9%E8%B1%A1-json-%E5%92%8Chash%E5%AF%B8%E5%AF%B9%E8%B1%A1" title="string存对象(json)和hash寸对象"></a>string存对象(json)和hash寸对象</h3>
<ul>
<li><code>string</code>存对象讲究整体性，一次性存一次性取，讲究读为主</li>
<li><code>hash</code>存对象，用<code>field</code>把属性隔离开，主要讲究得是更新操作比较有灵活性，讲究写为主</li>
<li>说通俗一点，当一个对象不需要频繁修改，只是存储之后查出来展示，那么用<code>string</code>来存是可以的，如果一个对象经常需要对各个属性进行修改，那么就使用<code>hash</code>，<code>hash</code>可以修改指定<code>field</code>的值</li>
</ul>
<h2 id="-23"><a class="markdownIt-Anchor" href="#-23"></a> <a href="#list" title="list"></a>list</h2>
<ul>
<li>数据存储需求：存储多个数据，并对数据进行存储空间的顺粗进行区分</li>
<li>需要的存储结构：一个存储空间保存多个数据，且通过数据可以体现进入顺序</li>
<li>list类型：保存多个数据，底层使用双向链表存储结构实现</li>
</ul>
<p>顺序表（查询快，增删慢），链表（查询慢，增删快），双向链表<br />
<img src="https://fantasy-ke.github.io/picx-images-hosting/redis/image.8ada3v182u.webp" alt="顺序表-链表-双向链表.png" /></p>
<h3 id="-24"><a class="markdownIt-Anchor" href="#-24"></a> <a href="#%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C" title="基础操作"></a>基础操作</h3>
<ul>
<li>
<p>添加/修改数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">lpush key value1 value2 ...  </span><br><span class="line">rpush key value1 value2 ...  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>获取数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">lrange key start stop  (lrange key 0 -1 表示查询整个列表)  </span><br><span class="line">lindex key index  </span><br><span class="line">llen key  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>获取并移除数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">lpop key  </span><br><span class="line">rpop key  </span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="-25"><a class="markdownIt-Anchor" href="#-25"></a> <a href="#%E6%89%A9%E5%B1%95%E6%93%8D%E4%BD%9C-2" title="扩展操作"></a>扩展操作</h3>
<ul>
<li>
<p>规定时间内获取并移除数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">blpop key1 key2 ... <span class="built_in">timeout</span>  </span><br><span class="line">brpop key1 key2 ... <span class="built_in">timeout</span>  </span><br></pre></td></tr></table></figure>
<p>就是当list没数据的时候，执行上面的命令会阻塞，等有其他客户端往上面监听的list添加数据，随后被取出，timeout为超时时间，单位为秒</p>
</li>
</ul>
<h3 id="-26"><a class="markdownIt-Anchor" href="#-26"></a> <a href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF-1" title="应用场景"></a>应用场景</h3>
<h4 id="-27"><a class="markdownIt-Anchor" href="#-27"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFA-2" title="业务场景A"></a>业务场景A</h4>
<p>微信朋友圈点赞，要求按点赞顺序显示点赞好友信息，如果取消点赞，则移除对应好友信息</p>
<p>解决方案：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">朋友圈Id -&gt; key -&gt; 举例 -&gt; a01  </span><br><span class="line">用户点赞 -&gt; rpush -&gt; 举例 -&gt; rpush a01 zhangsan lisi wangwu  </span><br><span class="line">展示 -&gt; lrange key start stop -&gt; 举例 -&gt; lrang a01 0 -1  </span><br><span class="line">取消点赞 -&gt; lrem key count value -&gt; 举例 -&gt; lrem a01 1 lisi  </span><br></pre></td></tr></table></figure>
<h3 id="-28"><a class="markdownIt-Anchor" href="#-28"></a> <a href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9-2" title="注意事项"></a>注意事项</h3>
<ul>
<li><code>list</code>中保存的数据都是string类型，数据总容量也是有限的，最多2的32次方-1个元素</li>
<li><code>list</code>具有索引的概念，但是操作数据时通常以队列的形式进行入队出队操作，或以栈的形式进行入栈出栈操作</li>
<li>获取全部数据操作结束索引设置为-1</li>
<li>list可以对数据进行分页操作，通常第一页的信息来自list，第2页及更多的信息通过数据库的形式加载</li>
</ul>
<h3 id="-29"><a class="markdownIt-Anchor" href="#-29"></a> <a href="#%E6%AF%94%E8%BE%83%E5%85%B8%E5%9E%8B%E7%9A%84%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AF" title="比较典型的业务场景"></a>比较典型的业务场景</h3>
<ul>
<li>twitter、微博中个人用户的关注列表需要按照用户的关注顺序进行展示，粉丝列表需要将最近关注的粉丝列在前面</li>
<li>新闻、资讯类网站将最新的新闻或咨询按照发生的时间顺序展示</li>
<li>企业运营过程中，系统将产出大量的运营数据，保障堕胎服务器操作日志的统一顺序输出</li>
</ul>
<p>上面的解决方案</p>
<ul>
<li>依赖list的数据具有顺序的特征对信息进行管理</li>
<li>使用栈模型解决最新消息的问题</li>
<li>使用队列模式解决多路信息汇总合并的问题</li>
</ul>
<h2 id="-30"><a class="markdownIt-Anchor" href="#-30"></a> <a href="#set" title="set"></a>set</h2>
<ul>
<li>存储需求：存储大量的数据，在查询方便提供更高的效率</li>
<li>需要的存储结构：能够保存大量的数据，高效的内部存储机制，便于查询</li>
<li>set类型：与hash存储结构完全相同，仅存储键，不存储值(nil)，并且值时不允许重复的</li>
</ul>
<h3 id="-31"><a class="markdownIt-Anchor" href="#-31"></a> <a href="#%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C-2" title="基本操作"></a>基本操作</h3>
<ul>
<li>添加数据：<code>sadd key member1 member2 ...</code></li>
<li>获取全部数据：<code>smembers key</code></li>
<li>删除数据：<code>srem key member1 member2 ...</code></li>
<li>获取集合数据总量：<code>scard key</code></li>
<li>判断集合中是否包含指定数据：<code>sismember key member</code></li>
<li>随机获取集合中指定数量的数据：<code>srandmember key [count]</code></li>
<li>随机获取集合中某个数据并将该数据移出集合：<code>spop key ...</code></li>
</ul>
<h3 id="-32"><a class="markdownIt-Anchor" href="#-32"></a> <a href="#%E6%89%A9%E5%B1%95%E6%93%8D%E4%BD%9C-3" title="扩展操作"></a>扩展操作</h3>
<ul>
<li>
<p>求两个集合的交、并、差集</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sinter key1 key2  </span><br><span class="line">sunion key1 key2  </span><br><span class="line">sdiff key1 key2  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>求两个集合的交、并、差集并存储到指定集合中</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sinterstore destination key1 key2  </span><br><span class="line">sunionstore destination key1 key2  </span><br><span class="line">sdiffstore destination key1 key2  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>将指定数据从原始集合中移动到目标集合中</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">smove <span class="built_in">source</span> destination member  </span><br></pre></td></tr></table></figure>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/redis/image.2dopwukw63.webp" alt="交并差.png" /></p>
</li>
</ul>
<h3 id="-33"><a class="markdownIt-Anchor" href="#-33"></a> <a href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF-2" title="应用场景"></a>应用场景</h3>
<h4 id="-34"><a class="markdownIt-Anchor" href="#-34"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFA-3" title="业务场景A"></a>业务场景A</h4>
<p>每位用户首次使用今日头条会设置3项爱好的内容，但是后期为了增加用户的活跃度、兴趣点，必须让用户对其他信息类别主键产生兴趣，增加客户留存都，该如何实现？</p>
<p>业务分析</p>
<ul>
<li>系统分析出各个分类的最新或最热点信息条目并组织成set集合</li>
<li>随机挑选其中部分信息</li>
<li>配合用户关注信息分类中的热点信息组成展示的全信息集合</li>
</ul>
<p><strong>redis应用于随机推荐类信息检索，例如热点歌单推荐，热点新闻推荐，热点旅游线路，应用APP推荐，大V推荐等</strong></p>
<h4 id="-35"><a class="markdownIt-Anchor" href="#-35"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFB-2" title="业务场景B"></a>业务场景B</h4>
<p>脉脉之类的APP中共同好友的功能，这里通过两个set进行交并差集的运算可以满足需求</p>
<ul>
<li>redis应用于同类信息的关联搜索，二度关联搜索，深度关联搜索</li>
<li>显示共同关注（交集）（一度）</li>
<li>显示共同好友（交集）（一度）</li>
<li>由用户A出发，获取到好友用户B的好友信息列表（一度）</li>
<li>由用户A出发，获取到好友用户B的购物清单列表（二度）</li>
<li>由用户A出发，获取到好友用户B的游戏充值列表（二度）</li>
</ul>
<h4 id="-36"><a class="markdownIt-Anchor" href="#-36"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFC-1" title="业务场景C"></a>业务场景C</h4>
<p>集团公司共具有12000名员工，内部OA系统中具有700多个角色，3000多个业务操作，23000多中数据，每个员工具有一个或多个角色，如何快速进行业务操作的权限校验？</p>
<p>解决思路：</p>
<ul>
<li>依赖<code>set</code>集合数据不重复的特征，依赖<code>set</code>集合<code>hash</code>存储结构特征完成数据过滤与快速查询</li>
<li>根据用户id获取用户所有角色</li>
<li>根据用户所有角色获取用户所有操作权限放入set集合</li>
<li>根据用户所有角色获取用户所有数据权限放入set集合</li>
</ul>
<h4 id="-37"><a class="markdownIt-Anchor" href="#-37"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFD" title="业务场景D"></a>业务场景D</h4>
<p>统计网站的PV、UV、IP</p>
<p>解决思路：</p>
<ul>
<li>利用<code>set</code>集合的数据去重特转增，记录各种访问数据</li>
<li>建立<code>string</code>类型数据，利用<code>incr</code>统计日访问量</li>
<li>建立<code>set</code>模型，记录不同cookie数量(UV)</li>
<li>建立<code>set</code>模型，记录不同IP数量(IP)</li>
</ul>
<h4 id="-38"><a class="markdownIt-Anchor" href="#-38"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFE" title="业务场景E"></a>业务场景E</h4>
<p>黑白名单</p>
<p>解决思路：</p>
<ul>
<li>基于经营战略设定问题用户发现、鉴别规则</li>
<li>周期性更新满足规则的用户黑名单，加入<code>set</code>集合</li>
<li>用户行为信息达到后于黑名单进行比对，确认行为去向</li>
<li>黑名单过滤IP地址：应用于开放游客访问权限的信息源</li>
<li>黑名单过滤设备信息：应用于限定访问设备的信息源</li>
<li>黑名单过滤用户：应用于基于访问权限的信息源</li>
</ul>
<h3 id="-39"><a class="markdownIt-Anchor" href="#-39"></a> <a href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9-3" title="注意事项"></a>注意事项</h3>
<ul>
<li><code>set</code>类型不允许数据重复，如果添加的数据在<code>set</code>中已经存在，将只保留一份</li>
<li><code>set</code>虽然于<code>hash</code>的存储结构相同，但是无法启用<code>hash</code>中存储值的空间</li>
</ul>
<h2 id="-40"><a class="markdownIt-Anchor" href="#-40"></a> <a href="#sorted-set" title="sorted_set"></a>sorted_set</h2>
<ul>
<li>存储需求：数据排序有利于数据的有效展示，需要提供一种可以根据自身特征进行排序的方式</li>
<li>需要的存储结构：新的存储模型，可以保存可排序的数据</li>
<li>sorted_set类型：在set的存储结构上添加可排序字段</li>
</ul>
<h3 id="-41"><a class="markdownIt-Anchor" href="#-41"></a> <a href="#%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C-1" title="基础操作"></a>基础操作</h3>
<ul>
<li>
<p>添加数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zadd key score1 member \[score2 member\] ...  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>获取全部数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zrang key start stop \[WITHSCORES\]  </span><br><span class="line">zrevrange key start stop \[WITHSCORES\]  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>删除数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zrem key member \[member ...\]  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>按条件获取数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zrangebyscore key min max \[WITHSCORES\] \[LIMIT\]  </span><br><span class="line">zrevrangebyscore key max min \[WITHSCORES\]  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>按条件删除数据</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zremrangebyrank key start stop  </span><br><span class="line">zremrangebyscore key min max  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>获取集合数据总量</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zcard key  </span><br><span class="line">zcard key min max  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>集合交、并操作</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zinterstore destination numkeys key \[key ...\]  </span><br><span class="line">zunionstore destination numkeys key \[key ...\]  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>获取数据对应的索引(排名)</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zrank key memeber  </span><br><span class="line">zrevrank key member  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>score值获取与修改</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">zscore key member  </span><br><span class="line">zincrby key increment member  </span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><strong>注意：</strong></p>
<ul>
<li>min与max用于限定搜索查询的条件</li>
<li>start与stop用于限定查询访问，作用于索引，表示开始和结束索引</li>
<li>offset与count用于限定查询范围，作用于查询结果，表示开始位置和数据总量</li>
</ul>
<h3 id="-42"><a class="markdownIt-Anchor" href="#-42"></a> <a href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF-3" title="应用场景"></a>应用场景</h3>
<h4 id="-43"><a class="markdownIt-Anchor" href="#-43"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFA-4" title="业务场景A"></a>业务场景A</h4>
<p>海选投票、各种TopN排行榜、聊天室活跃度统计、游戏好友亲密度</p>
<p>解决方案：通过获取索引</p>
<h4 id="-44"><a class="markdownIt-Anchor" href="#-44"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFB-3" title="业务场景B"></a>业务场景B</h4>
<p>体验VIP功能，当体验VIP到期后，如何有效管理此类信息，即便对于正式VIP用户也应该存在对应的管理方式。网站定期开启投票、讨论、限期进行，逾期作废，如何有效管理此类过期信息</p>
<p>解决方案：</p>
<ul>
<li>对基于时间线限定的任务处理，将处理时间记录为<code>score</code>值，利用顺序功能分区处理的先后顺序</li>
<li>记录下一个要处理的时间，当到期后处理对应任务，移除redis中的记录，并记录下一个要处理的时间</li>
<li>当新任务加入时，判断并更新当前下一个要处理的任务时间</li>
<li>为提升<code>sorted_set</code>的性能，通常将任务根据特征存储成若干个<code>sorted_set</code>，例如1小时内、1天内、周内、月内、季内、年内等，操作时逐级提升，将即将操作的若干任务纳入到1小时内处理的队伍中</li>
</ul>
<h4 id="-45"><a class="markdownIt-Anchor" href="#-45"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFC-2" title="业务场景C"></a>业务场景C</h4>
<p>任务/消息权重设定应用：当任务或消息待处理，形成了任务队列或消息队列时，对于高优先级的任务要保障对其优先处理</p>
<p>解决方案：</p>
<ul>
<li>对于带权重的任务，优先处理权重高的任务，采用score记录权重即可</li>
</ul>
<h3 id="-46"><a class="markdownIt-Anchor" href="#-46"></a> <a href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9-4" title="注意事项"></a>注意事项</h3>
<ul>
<li><code>score</code>保存的数据存储空间是64位</li>
<li><code>score</code>保存的数据也可以是个双精度的double值，基于双精度浮点数的特征，可能会丢失精度，使用时要慎重</li>
<li><code>sorted_set</code>底层存储还是基于<code>set</code>结构的，因此数据不能重复，如果重复添加相同的数据，<code>score</code>值将被反复覆盖，保留最后一次修改的结果</li>
</ul>
<h1 id="-47"><a class="markdownIt-Anchor" href="#-47"></a> <a href="#%E5%AE%9E%E8%B7%B5%E6%A1%88%E4%BE%8B" title="实践案例"></a>实践案例</h1>
<h2 id="-48"><a class="markdownIt-Anchor" href="#-48"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFA-5" title="业务场景A"></a>业务场景A</h2>
<p>人工智能领域的语义识别与自动对话将是未来服务业机器人应答呼叫体系中的重要技术，百度自研用户评价语义识别服务，免费开放给企业试用，同时训练百度自己的模型。现对试用用户的使用行为进行限速，限制每个用户每分钟最多发起10次调用</p>
<p>解决方案：</p>
<ul>
<li>设计计数器，记录调用次数，用于控制业务执行次数，以用户id作为key，使用次数为value</li>
<li>在调用前获取次数，判断是否超过限定次数
<ul>
<li>不超过次数的情况下，每次调用技术+1</li>
<li>超过次数则业务调用失败，计数-1</li>
</ul>
</li>
<li>为计时器设置生命周期为指定周期，例如1秒/分钟，自动清空周期内使用次数</li>
</ul>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/redis/image.5c100ctctw.webp" alt="业务场景A.png" /></p>
<p>解决方案改良：</p>
<ul>
<li>取消最大值的判断，利用incr操作超过最大值抛出异常的形式替代每次判断是否大于最大值</li>
<li>判断值是否为nil
<ul>
<li>如果是，设置为数值的Max-次数</li>
<li>如果不是，计数+1</li>
<li>业务调用失败，计数-1</li>
</ul>
</li>
<li>遇到异常即+操作超过上限，视为使用达到上限</li>
</ul>
<p><img src="https://fantasy-ke.github.io/picx-images-hosting/redis/image.2krxsa7crt.webp" alt="业务场景A改良.png" /></p>
<h2 id="-49"><a class="markdownIt-Anchor" href="#-49"></a> <a href="#%E4%B8%9A%E5%8A%A1%E5%9C%BA%E6%99%AFB-4" title="业务场景B"></a>业务场景B</h2>
<p>使用微信的过程中，当微信接收消息后，会默认将最近接受的消息置顶，当多个好友及关注的订阅号同时发送消息时，该顺序会不停的进行交替。同时还可以将重要的会话设置为置顶。一旦用户里离线后，再次打开微信时，消息该按照什么样的顺序显示？</p>
<p>解决方案：</p>
<ul>
<li>依赖<code>list</code>的数据具有顺序的特征对消息进行管理，将<code>list</code>结构作为栈使用</li>
<li>对指定与普通会话分别创建独立的<code>list</code>分别管理</li>
<li>当某个<code>list</code>中接收到用户消息后，将消息发送方的<code>id</code>从<code>list</code>的一侧加入<code>list</code>(此处设定左侧)</li>
<li>多个<code>消息id</code>发出的消息反复入栈会出现问题，在入栈前无论是否具有当前<code>id</code>对应的消息，先删除对应<code>id</code></li>
<li>推送消息时先推送置顶会话<code>list</code>，再推送普通会话<code>list</code>，推送完成的<code>list</code>清除所有数据</li>
<li>消息的数量，也就是微信用户对话数量采用计数器的思路另行记录，伴随<code>list</code>操作同步更新</li>
</ul>
<h1 id="-50"><a class="markdownIt-Anchor" href="#-50"></a> <a href="#key%E9%80%9A%E7%94%A8%E6%93%8D%E4%BD%9C" title="key通用操作"></a>key通用操作</h1>
<h2 id="-51"><a class="markdownIt-Anchor" href="#-51"></a> <a href="#key%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C" title="key基本操作"></a>key基本操作</h2>
<ul>
<li>删除指定key：<code>del key</code></li>
<li>获取key是否存在：<code>exists key</code></li>
<li>获取key的类型：<code>type key</code></li>
</ul>
<h2 id="-52"><a class="markdownIt-Anchor" href="#-52"></a> <a href="#key%E7%9A%84%E6%97%B6%E6%95%88%E6%80%A7%E6%8E%A7%E5%88%B6" title="key的时效性控制"></a>key的时效性控制</h2>
<ul>
<li>
<p>为指定key设置有效期</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">expire key seconds  </span><br><span class="line">pexpire key milliseconds  </span><br><span class="line">expireat key timestamp  </span><br><span class="line">pexpireat key milliseconds-timestamp  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>获取key的有效实践</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ttl key  </span><br><span class="line">pttl key  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>切换key从时效性转换为永久性</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">persist key  </span><br></pre></td></tr></table></figure>
<h2 id="-53"><a class="markdownIt-Anchor" href="#-53"></a> <a href="#key%E7%9A%84%E6%9F%A5%E8%AF%A2%E6%A8%A1%E5%BC%8F" title="key的查询模式"></a>key的查询模式</h2>
</li>
<li>
<p>查询key：<code>keys parttern</code>，查询模式规则：</p>
<ul>
<li><code>*</code>：匹配任意数量的任意符号</li>
<li><code>?</code>：匹配一个任意字符</li>
<li><code>[]</code>：匹配一个指定符号</li>
</ul>
<p>举例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">keys \* -&gt; 查询所有  </span><br><span class="line">keys it\* -&gt; 查询所有以it开头  </span><br><span class="line">keys \*save -&gt; 查询所有以save结尾  </span><br><span class="line">keys ??user -&gt; 查询所有前面两个任意字符，后面以user结尾  </span><br><span class="line">keys user:<span class="string">&quot; -&gt; 查询所有以user:开头，后面一个任意字符  </span></span><br><span class="line"><span class="string">keys u\[st\]er:1 -&gt;查询所有以u开头，以er:1结尾，中间包含字符s或t  </span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="-54"><a class="markdownIt-Anchor" href="#-54"></a> <a href="#key%E7%9A%84%E5%85%B6%E4%BB%96%E6%93%8D%E4%BD%9C" title="key的其他操作"></a>key的其他操作</h2>
<ul>
<li>
<p>为key改名</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rename key newkey  </span><br><span class="line">renamenx key newkey  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>对所有key排序</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">sort</span>  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>其他key通用操作</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">help</span> @generic  </span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="-55"><a class="markdownIt-Anchor" href="#-55"></a> <a href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E9%80%9A%E7%94%A8%E6%93%8D%E4%BD%9C" title="数据库通用操作"></a>数据库通用操作</h1>
<h2 id="-56"><a class="markdownIt-Anchor" href="#-56"></a> <a href="#key%E7%9A%84%E9%87%8D%E5%A4%8D%E9%97%AE%E9%A2%98" title="key的重复问题"></a>key的重复问题</h2>
<ul>
<li>key是由程序员定义的</li>
<li>redis在使用过程中，伴随着操作数据量的增加，会出现大量的数据以及对应的key</li>
<li>数据不区分种类、类别混在在一起，极易出现重复或冲突</li>
</ul>
<p>解决方案：</p>
<ul>
<li>redis为每个服务提供有16个数据库，编号从0到15</li>
<li>每个数据库之间的数据相互独立</li>
</ul>
<h2 id="-57"><a class="markdownIt-Anchor" href="#-57"></a> <a href="#%E5%9F%BA%E6%9C%AC%E6%93%8D%E4%BD%9C-3" title="基本操作"></a>基本操作</h2>
<ul>
<li>
<p>切换数据库</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> index  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>其他操作</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">quit  </span><br><span class="line">ping  </span><br><span class="line"><span class="built_in">echo</span> message  </span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="-58"><a class="markdownIt-Anchor" href="#-58"></a> <a href="#%E5%85%B6%E4%BB%96%E6%93%8D%E4%BD%9C" title="其他操作"></a>其他操作</h2>
<ul>
<li>
<p>数据移动</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">move key db  </span><br></pre></td></tr></table></figure>
</li>
<li>
<p>数据清除</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dbsize --库里有多少个key  </span><br><span class="line">flushdb  --清空当前数据库  </span><br><span class="line">flushall --清空有数据库</span><br></pre></td></tr></table></figure></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">







<div class="license">
  <div class="license-title">Redis基础</div>
  <div class="license-link">
    <a href="https://blog.fantasyke.cn/posts/26216/">https://blog.fantasyke.cn/posts/26216/</a>
  </div>
  <div class="license-meta">
    <div class="license-meta-item">
      <div class="license-meta-title">本文作者</div>
      <div class="license-meta-text">
          Fantasy-ke
      </div>
    </div>
      <div class="license-meta-item">
        <div class="license-meta-title">发布于</div>
        <div class="license-meta-text">
          2023-05-29
        </div>
      </div>
      <div class="license-meta-item">
        <div class="license-meta-title">更新于</div>
        <div class="license-meta-text">
          2024-12-17
        </div>
      </div>
    <div class="license-meta-item">
      <div class="license-meta-title">许可协议</div>
      <div class="license-meta-text">
          禁止转载引用
      </div>
    </div>
  </div>
  <div class="license-statement">
      如需转载或引用本文，请先获得作者授权！
  </div>
</div>
          <div class="reward-container">
  <div>Buy me a coffee</div>
  <button>
    Donate
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="Fantasy-ke WeChat Pay">
        <span>WeChat Pay</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>Welcome to my other publishing channels</span>

  <div class="social-list">

      <div class="social-item">
          <a target="_blank" class="social-link" href="https://github.com/fantasy-ke">
            <span class="icon">
              <i class="fab fa-github"></i>
            </span>

            <span class="label">GitHub</span>
          </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/Redis/" rel="tag"><i class="fa fa-tag"></i> Redis</a>
              <a href="/tags/NOSQL/" rel="tag"><i class="fa fa-tag"></i> NOSQL</a>
          </div>

        
  <div class="social-like a2a_kit a2a_kit_size_32 a2a_default_style">
    <a class="a2a_dd" target="_blank" rel="noopener" href="https://www.addtoany.com/share"></a>
      <a class="a2a_button_facebook"></a>
      <a class="a2a_button_twitter"></a>
      <a class="a2a_button_telegram"></a>
      <a class="a2a_button_wechat"></a>
  </div>

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/posts/1297/" rel="prev" title="Redis进阶">
                  <i class="fa fa-angle-left"></i> Redis进阶
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/posts/59211/" rel="next" title="RabbitMQ进阶">
                  RabbitMQ进阶 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2021 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-solid fa-t-rex"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Fantasy-ke</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>Word count total: </span>
    <span title="Word count total">72k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>Reading time total &asymp;</span>
    <span title="Reading time total">4:21</span>
  </span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="Total Visitors">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="Total Views">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div> 
<script src="https://cdn.jsdelivr.net/npm/moment@2.22.2/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment-precise-range-plugin@1.3.0/moment-precise-range.min.js"></script>
<script>
  var now = new Date();
  function timer() {
    var grt= new Date("03/12/2022 13:14:21");//此处修改你的建站时间或者网站上线时间
    now.setTime(now.getTime()+250);
    days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
    hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
    if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
    seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
    var ages = `${dnum}天${hnum}小时${mnum}分${snum}秒`;
    div.innerHTML = `本站已安全运行 ${ages} 🐶`;
  }
  var div = document.createElement("div");
  //插入到copyright之后
  var copyright = document.querySelector(".busuanzi-count");
  document.querySelector(".footer-inner").insertBefore(div, copyright.nextSibling);
  timer();
  setInterval("timer()",1000)
</script>


<div class="footer-menu">
    <a style="color: chocolate;" href="/tags/">文章标签</a> · <a style="color: chocolate;"  href="/policy/">网站政策</a> · <a style="color: chocolate;"  href="/photos/">文章相册</a>
</div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2ZhbnRhc3kta2U=" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.31/fancybox/fancybox.umd.js" integrity="sha256-a+H7FYzJv6oU2hfsfDGM2Ohw/cR9v+hPfxHCLdmCrE8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>


  <script src="/js/third-party/addtoany.js"></script>

  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5.7/lib/darkmode-js.min.js"></script>

<script>
var options = {
  bottom: '64px',
  right: 'unset',
  left: '32px',
  time: '0.5s',
  mixColor: 'transparent',
  backgroundColor: 'transparent',
  buttonColorDark: '#100f2c',
  buttonColorLight: '#fff',
  saveInCookies: true,
  label: '🌓',
  autoMatchOsTheme: true
}
const darkmode = new Darkmode(options);
window.darkmode = darkmode;
darkmode.showWidget();
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.8.0/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"fantasy-ke","repo":"fantasy-ke.github.io","client_id":"Ov23li8eCFrhnzfiGx5T","client_secret":"ce23581c2059392ebd00afd08d5ba43f767fd1b1","admin_user":"fantasy-ke","distraction_free_mode":true,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","labels":"gitalk","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.8.0/gitalk.min.js","integrity":"sha256-MVK9MGD/XJaGyIghSVrONSnoXoGh3IFxLw0zfvzpxR4="},"path_md5":"765cba667afc5367e57ad64b728c730d"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>


<script src="/js/minigrid.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script data-pjax type="text/javascript">
var album = document.querySelector(".album");
if (album) {
  // 相册列表 JSON 数据
  var imgDataPath = album.getAttribute('json-src');
  // 照片存储路径
  var imgPath = album.getAttribute('photo-src');
  // 最多显示数量
  var imgMaxNum = 50;
  // 获取窗口大小以决定图片宽度
  var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var imageWidth;

  if (windowWidth < 768) {
    imageWidth = 145; // 移动端图片宽度
  } else {
    imageWidth = 235;
  }

  // 生成相册
  var linkDataPath = imgDataPath;
  var photo = {
    page: 1,
    offset: imgMaxNum,
    init: function () {
      var that = this;
      $.getJSON(linkDataPath, function (data) {
          that.render(that.page, data);
      });
    },
    render: function (page, data) {
      var begin = (page - 1) * this.offset;
      var end = page * this.offset;
      if (begin >= data.length) return;
      var imgNameWithPattern, imgName, imageSize, imageX, imageY, li = "";
      for (var i = begin; i < end && i < data.length; i++) {
        imgNameWithPattern = data[i].path;
        imgName = data[i].name;
        imageSize = data[i].size;
        li += '<div class="card" style="width:' + imageWidth + 'px" >';
        li += '<div class="album-photo" style="height:' + imageWidth + 'px" >';
        li += '<a class="fancybox fancybox.image" href="' + imgPath + imgNameWithPattern + '" itemscope="" itemtype="http://schema.org/ImageObject" itemprop="url" data-fancybox="group" rel="group" data-caption="' + imgName + '" title="' +  imgName + '">';
        li += '<img data-src="' + imgPath + imgNameWithPattern + '" src="' + imgPath + imgNameWithPattern + '" alt="' +  imgName + '" data-loaded="true">';
        li += '</a>';
        li += '</div>';
        li += '</div>';
      }
      album.insertAdjacentHTML('beforeend', li);
      this.minigrid();
    },
    minigrid: function () {
      var grid = new Minigrid({
        container: '.album',
        item: '.card',
        gutter: 12
      });
      grid.mount();
      window.addEventListener('resize', function () {
        grid.mount();
      });
    }
  };
  photo.init();
}
</script>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":170,"height":330},"mobile":{"show":true},"react":{"opacity":0.7},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
